package handler

import (
	"errors"
	"send-id-num/internal/repository"

	"github.com/gin-gonic/gin"
	"send-id-num/pkg/http"
)

const (
	One = 1
	Two = 2
)

type DetailResp struct {
	Infos repository.IdNums `json:"infos"`
	User  string            `json:"user"`
}

var Source = map[string]int{"one": One, "two": Two}

func Detail(c *gin.Context) {
	userInfo, err := http.ParseUserToken(c.Request.Header.Get("Authorization"))
	if err != nil {
		c.JSON(http.StatusOK, http.LoginExpire("登录过期！"))
		return
	}
	// 获取
	// redis 获取最大数
	maxHave, err := repository.GetMaxHave(userInfo.Source)
	if err != nil {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("redis GetMaxHave err！"+err.Error()))
		return
	}
	// 获取用户已有的
	idNums, err := repository.GetUserIdNum(userInfo.UserId, userInfo.Source)
	if err != nil {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("GetUserIdNum err！"+err.Error()))
		return
	}
	data := DetailResp{}
	data.User = userInfo.UserId.User().Name
	// 校验数量
	// 满足返回
	if len(idNums) >= maxHave {
		data.Infos = idNums
		c.JSON(http.StatusOK, http.SuccessResData(data))
		return
	}
	// 说明小于,不满足再获取
	dif := maxHave - len(idNums)
	newIdNums, err := userInfo.UserId.GetIdNumsByCount(dif)
	if err != nil {
		c.JSON(http.StatusOK, http.FailureResDefaultCode("GetIdNumsByCount err"+err.Error()))
		return
	}
	idNums = append(idNums, newIdNums...)
	data.Infos = idNums
	// 更新
	c.JSON(http.StatusOK, http.SuccessResData(data))

}

func source(sourceString string) (source int, err error) {
	if sourceString == "" {
		err = errors.New("get path err")
		return
	}
	source, ok := Source[sourceString]
	if !ok {
		err = errors.New("source incorrect")

		return
	}
	return
}
